package com.data.platform.datasource.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.data.platform.core.model.UserDto;
import com.data.platform.core.utils.AuthUtils;
import com.data.platform.datasource.model.BaseDo;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 公共字段属性值自动填充
 */
public class DefaultFieldHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseDo) {
            BaseDo baseDO = (BaseDo) metaObject.getOriginalObject();
            LocalDateTime now = LocalDateTime.now();
            if (Objects.isNull(baseDO.getCreateTime())) {
                baseDO.setCreateTime(now);
            }

            if (Objects.isNull(baseDO.getUpdateTime())) {
                baseDO.setUpdateTime(now);
            }

            // 获取登录用户信息
            UserDto userDTO = (UserDto) AuthUtils.getAuthenticate().getPrincipal();

            if (Objects.nonNull(userDTO) && Objects.isNull(baseDO.getCreateBy())) {
                baseDO.setCreateBy(userDTO.getNickname());
            }

            if (Objects.nonNull(userDTO) && Objects.isNull(baseDO.getUpdateBy())) {
                baseDO.setUpdateBy(userDTO.getNickname());
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = getFieldValByName("updateTime", metaObject);

        if (Objects.isNull(updateTime)) {
            setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }

        UserDto userDTO = (UserDto) AuthUtils.getAuthenticate().getPrincipal();

        Object modifier = getFieldValByName("updateBy", metaObject);
        if (Objects.nonNull(userDTO) && Objects.isNull(modifier)) {
            setFieldValByName("updateBy", userDTO.getNickname(), metaObject);
        }

    }
}
